import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'index.dart';
import 'widegts/index.dart';
import '../../../common/values/images.dart';
import '../../../common/services/amap_location_service.dart';

class HomeIndexPage extends GetView<HomeIndexController> {
  const HomeIndexPage({super.key});

  // 主视图
  Widget _buildView() {
    return Obx(() {
      // 🔄 加载状态
      if (controller.isLoading.value && controller.activities.isEmpty) {
        return const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(
                color: Colors.white,
              ),
              SizedBox(height: 16),
              Text(
                '加载活动中...',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ],
          ),
        );
      }
      
      // 📭 空状态
      if (controller.activities.isEmpty) {
        return _buildEmptyView();
      }
      
      // 🎯 活动列表 - 使用Listener监听原始指针事件（下拉刷新必须用Listener）
      return Listener(
        onPointerMove: (details) {
          // 检测是否在第一个页面且向下拉动
          if (controller.currentPageIndex.value == 0 && details.delta.dy > 0) {
            // 🔥 移除频繁的日志输出，减少性能开销
            controller.updatePullDistance(details.delta.dy);
          }
        },
        onPointerUp: (details) {
          if (controller.currentPageIndex.value == 0) {
            // 🔥 移除频繁的日志输出，减少性能开销
            controller.checkRefreshTrigger();
          }
        },
        child: Stack(
          children: [
            // PageView内容
            PageView.builder(
              controller: controller.pageController,
              scrollDirection: Axis.vertical,
              physics: const BouncingScrollPhysics(),
              onPageChanged: controller.onPageChanged,
              // 🔥 只显示活动列表，不显示额外的状态页面
              itemCount: controller.activities.length,
              itemBuilder: (context, index) {
                final activity = controller.activities[index];
                return ActivityCard(
                  activity: activity,
                  index: index,
                  controller: controller,
                );
              },
            ),
            
            // 🔄 下拉刷新指示器（在背景上显示）
            if (controller.isRefreshing.value)
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: _buildRefreshIndicator(),
              ),
            
            // 🔄 下拉距离提示（在AppBar下方显示）
            if (controller.pullDistance.value > 0 && !controller.isRefreshing.value)
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: _buildPullIndicator(),
              ),
          ],
        ),
      );
    });
  }
  
  // 🔄 构建下拉距离指示器（显示拖动进度）
  Widget _buildPullIndicator() {
    final pullDistance = controller.pullDistance.value;
    final isReady = pullDistance >= 80;
    final pullProgress = (pullDistance / 80).clamp(0.0, 1.0);
    
    // 🔥 动态计算容器高度，最小80px（确保内容不溢出）
    final containerHeight = pullDistance.clamp(80.0, 150.0);
    
    return Container(
      height: containerHeight,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            isReady 
                ? const Color(0xFF4CAF50).withOpacity(0.6)  // 🔥 达到阈值时显示绿色
                : Colors.white.withOpacity(0.4),
            Colors.transparent,
          ],
        ),
      ),
      child: SafeArea(
        child: Center(
          // 🔥 使用SingleChildScrollView避免溢出
          child: SingleChildScrollView(
            physics: const NeverScrollableScrollPhysics(),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 🔥 图标和文字横向排列
                Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 🔄 旋转的下拉图标
                    Transform.rotate(
                      angle: pullProgress * 3.14159, // 0 到 180 度
                      child: Icon(
                        isReady ? Icons.refresh : Icons.arrow_downward,
                        color: Colors.white,
                        size: 20, // 🔥 减小图标尺寸，避免溢出
                      ),
                    ),
                    const SizedBox(width: 8),
                    // 📝 提示文字（与图标同行）
                    Text(
                      isReady ? '松开刷新' : '下拉刷新',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13, // 🔥 减小字体，避免溢出
                        fontWeight: isReady ? FontWeight.bold : FontWeight.w500,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
                // 📊 进度提示（只在未达到阈值且有足够空间时显示）
                if (!isReady && pullDistance > 120) ...[
                  const SizedBox(height: 4),
                  Text(
                    '${(pullProgress * 100).toInt()}%',
                    style: const TextStyle(
                      color: Colors.white70,
                      fontSize: 11,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  // 🔄 构建刷新指示器
  Widget _buildRefreshIndicator() {
    return Container(
      height: 100,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.black.withOpacity(0.6),
            Colors.transparent,
          ],
        ),
      ),
      child: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(
                color: Colors.white,
                strokeWidth: 2.5,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '正在刷新...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 13,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 📭 构建空视图
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.explore_outlined,
            size: 80,
            color: Colors.white54,
          ),
          const SizedBox(height: 20),
          const Text(
            '附近暂无活动',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 10),
          Obx(() => Text(
            Get.find<AmapLocationService>().locationText,
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 14,
            ),
          )),
          const SizedBox(height: 30),
          ElevatedButton.icon(
            onPressed: controller.refreshActivities,
            icon: const Icon(Icons.refresh),
            label: const Text('刷新试试'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.white,
              foregroundColor: Colors.black87,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(24),
              ),
            ),
          ),
        ],
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeIndexController>(
      init: HomeIndexController(),
      id: "home_index",
      builder: (_) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          backgroundColor: Colors.black,
          appBar: _buildAppBar(),
          body: _buildView(),
        );
      },
    );
  }

  // 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.transparent,
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,
        statusBarBrightness: Brightness.dark,
      ),
      // 右上角：消息icon
      leading: Container(
        margin: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.3),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: Colors.white.withOpacity(0.2),
            width: 0.5,
          ),
        ),
        child: Stack(
          children: [
            IconButton(
              onPressed: controller.onMessageTap,
              icon: Image.asset(
                AssetsImages.msgPng,
                width: 22,
                height: 22,
                color: Colors.white,
              ),
            ),
            // 🔔 未读消息小红点（只显示红点，不显示数字）
            Obx(() {
              if (controller.unreadCount.value > 0) {
                return Positioned(
                  right: 8,
                  top: 8,
                  child: Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: Colors.white,
                        width: 1.5,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.red.withOpacity(0.5),
                          blurRadius: 4,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            }),
          ],
        ),
      ),
      // 中间：地理位置文本
      title: Obx(() {
        final locationService = Get.find<AmapLocationService>();
        return GestureDetector(
          onTap: controller.onLocationTap,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 0.5,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 🔥 定位状态图标
                Icon(
                  locationService.isSuccess 
                      ? Icons.location_on 
                      : Icons.location_off,
                  size: 16,
                  color: locationService.isSuccess 
                      ? Colors.white 
                      : Colors.orange,
                ),
                const SizedBox(width: 6),
                // 位置文本
                Flexible(
                  child: Text(
                    locationService.locationText,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        );
      }),
      centerTitle: true,
      // 右侧：图片指示器（显示当前活动的图片数量）
      actions: [
        Obx(() {
          // 如果没有活动或没有图片，不显示指示器
          if (controller.activities.isEmpty || controller.currentImageCount.value == 0) {
            return const SizedBox(width: 56);
          }
          
          // 显示当前图片索引/总图片数
          final currentImageIndex = controller.currentImageIndex.value + 1;
          final totalImages = controller.currentImageCount.value;
          
          return Container(
            margin: const EdgeInsets.all(8),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.3),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 0.5,
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(
                  Icons.photo_library_outlined,
                  color: Colors.white,
                  size: 16,
                ),
                const SizedBox(width: 6),
                Text(
                  '$currentImageIndex/$totalImages',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          );
        }),
      ],
    );
  }
}
